<!-- GoodSku -->
<template>
  <div class="sku">
    <!-- 规格 -->
    <div class="sku-list-wrap">

      <!-- 规格类型 -->
      <div v-for="(item, $index) in attributeParamList" :key="$index" class="sku-lists">
        <div class="sku-name">
          <span class="sku-label">规格名：</span>
          <el-input :class="['sku-input', {'is-error': item.isError}]" :size="size" v-model="item.name" @change="handleDataChange(item)"></el-input>
          <!-- 规格名 name -->
          <el-checkbox v-if="$index === 0" class="sku-checkbox" v-model="item.havaIconChecked">添加规格图片</el-checkbox>
          <span class="sku-delete" @click="handleRemove(1, $index, item)">删除</span>
        </div>
        <div class="sku-value">
          <span class="sku-label">规格值：</span>
          <div class="sku-value-wrap">
            <div class="sku-value-list" v-for="(items, index) in item.attributes" :key="index">
              <el-input :class="['sku-input', {'is-error': items.isError}]" :size="size" v-model="items.value" @change="handleDataChange(items, item)"></el-input>
              <!-- 规格值 value -->
              <span class="delete-icon" @click="handleRemove(2, $index, index, item, items)">
                <i class="el-icon-close"></i>
              </span>
              <div v-if="item.havaIconChecked">
                <UploadImg v-model="items.imageUrl" :limitSize="{width: 340, height: 340}"></UploadImg>
              </div>
            </div>
          </div>
          <span class="sku-add-value-ele" @click="handleAddSkuValue($index)">添加规格值</span>
        </div>
      </div>
      <!-- 规格类型 -->

      <div style="margin-top: 10px;">
        <template v-if="addBtnDis">
          <el-popover placement="top" title="" width="120" trigger="hover" content="最多支持三组规格">
            <el-button slot="reference" style="cursor: not-allowed;" @click="handleAddSku" type="info" size="small"
                       icon="el-icon-plus">添加规格名</el-button>
          </el-popover>
        </template>
        <template v-else>
          <el-button :disabled="addBtnDis" @click="handleAddSku" type="primary" size="small" icon="el-icon-plus">添加规格名</el-button>
        </template>
        <!-- <el-button :disabled="!attributeParamList || attributeParamList.length < 1" @click="handleSkuDetailData" style="margin-left: 10px;"
                   type="primary" size="small">组合数据</el-button> -->
      </div>
      <div class="error-tips">注意：添加、删除规格名都将重新置空规格明细中价格、库存等内容，请谨慎操作！</div>

      <!-- 规格明细 -->
      <div class="sku-detail">
        <div class="sku-label">规格明细：</div>
        <div class="sku-detail-table" v-if="skuDetailData && skuDetailData.length >= 1" v-loading="dataDealLoading">
          <div class="sku-row table-h">
            <div v-for="(item, index) in skuDetailTableHead" :key="index" class="sku-cell">
              <span>{{item}}</span>
            </div>
          </div>
          <div class="table-body">
            <div v-for="(item, index) in skuDetailData" :key="index" class="sku-row">
              <div class="sku-cell">
                <span>{{item.sp1}}</span>
              </div>
              <div class="sku-cell" v-if="attributeParamList.length >= 2">
                <span>{{item.sp2}}</span>
              </div>
              <div class="sku-cell" v-if="attributeParamList.length >= 3">
                <span>{{item.sp3}}</span>
              </div>
              <div class="sku-cell">
                <el-input v-model="item.usePointLimit" :disabled="priceType ==='3'" size="small"></el-input>
              </div>
              <div class="sku-cell">
                <el-input v-model="item.price" :disabled="priceType ==='2'" size="small"></el-input>
              </div>
              <div class="sku-cell">
                <el-input v-model="item.stock" size="small"></el-input>
              </div>
              <div class="sku-cell">
                <el-input v-model="item.weight" size="small"></el-input>
              </div>
              <div class="sku-cell">
                <el-input v-model="item.costPrice" size="small"></el-input>
              </div>
              <!-- <div class="sku-cell">
                <el-input v-model="item.sale" size="small"></el-input>
              </div> -->
              <div class="sku-cell sku-code">
                <el-input style="width: 140px;" v-model="item.skuCode" size="small"></el-input>
                <!-- <ProductSn v-model="item.skuCode" size="small"></ProductSn> -->
              </div>
            </div>
          </div>
          <div class="table-footer">
            <div>
              <span>共{{skuDetailData.length}}条&nbsp; 批量设置：</span>
              <span v-for="item in batchSetupList" :key="item.key">
                <span class="pitch-ele disabled" v-if="item.key==='usePointLimit' && priceType === '3'">{{item.name}}</span>
                <span class="pitch-ele disabled" v-else-if="item.key==='price'  && priceType === '2' ">{{item.name}}</span>
                <span @click="handleBatchSet(item)" class="pitch-ele" v-else>{{item.name}}</span>
              </span>
              <span class="pitch-ele" @click="handleSetProductSn">自动设置商品编码</span>
            </div>

          </div>
        </div>

      </div>
      <!-- 规格明细 -->
    </div>
    <!-- 规格 -->

  </div>
</template>

<script>
import UploadImg from '@/components/Upload/imgSignleUpload'
import { GetProductSn } from '@/api/onlineMan'
// import ProductSn from '@/components/ProductSn'
export default {
  name: 'GoodSku',
  components: { UploadImg },
  data () {
    return {
      productSnList: [],
      size: 'medium',
      addBtnDis: false, // 是否再添加规格
      attributeParamList: [],
      skuDetailTableHead: [], // 规格明细表头
      // 积分 重量
      // tableHead: ['积分', '价格(元)', '库存', '重量(kg)', '成本价', '销量', '商品编码'],
      tableHead: ['积分', '价格(元)', '库存', '重量(kg)', '成本价', '商品编码'],
      // tableHeadKey: ['usePointLimit', 'price', 'stock', 'weight', 'costPrice', 'sale', 'skuCode'],
      tableHeadKey: ['usePointLimit', 'price', 'stock', 'weight', 'costPrice', 'skuCode'],
      batchSetupList: [
        { name: '积分', key: 'usePointLimit', regType: 1 },
        { name: '价格', key: 'price', regType: 2 },
        { name: '库存', key: 'stock', regType: 1 },
        { name: '重量', key: 'weight', regType: 2 },
        { name: '成本价', key: 'costPrice', regType: 2 }
        // { name: '销量', key: 'sale', regType: 1 }
      ],
      skuDetailData: [], // 规格明细数据
      skuDetailDataNum: 60, // 规格明细数据限制条数
      lastTimeSkuData: [], // 上一份规格明细数据
      dataDealLoading: false
    }
  },
  props: {
    priceType: {
      type: String,
      default: '1'
    }
  },
  watch: {
    'priceType': function (val) {
      this.skuDetailData.forEach(e => {
        if (val === '2') e.price = '0'
        if (val === '3') e.usePointLimit = '0'
      })
    },
    'skuDetailData': {
      deep: true,
      handler: function (val) {
        this.upEmitData(val)
      }
    }
  },
  computed: {},
  mounted () {
    this.getSn()
    this.handleSkuDetailData()
    // this.testData()
  },
  methods: {
    testData () {
      const modelSku = {
        attributes: [
        ],
        havaIcon: 0,
        havaIconChecked: false,
        name: '1',
        sort: 0,
        isError: false
      }
      this.attributeParamList.push(modelSku)
      for (let index = 0; index < 15; index++) {
        const modelSkuVal = { isError: false, imageUrl: '', value: 'val' + index, uniqueKey: this.produceUniqueKey() }
        this.attributeParamList[0].attributes.push(modelSkuVal)
      }
    },
    // 添加规格名
    handleAddSku () {
      const len = this.attributeParamList.length || 0
      if (len >= 3) {
        this.addBtnDis = true
        this.$message.warning('规格名最多只能添加三个！')
      } else {
        this.addBtnDis = false
        // 模板sku规格名数据
        const modelSku = {
          attributes: [
            {
              imageUrl: '',
              value: '',
              uniqueKey: this.produceUniqueKey()
            }
          ],
          havaIcon: 0,
          havaIconChecked: false,
          name: '',
          sort: 0,
          isError: false
        }
        this.$nextTick(() => {
          this.attributeParamList.push(modelSku)
          if (this.attributeParamList.length >= 3) {
            this.addBtnDis = true
          }
          this.handleSkuDetailData()
        })
      }
    },
    // 添加规格值
    handleAddSkuValue ($index) {
      this.$nextTick(() => {
        // 模板sku规格值数据
        const modelSkuVal = { isError: false, imageUrl: '', value: '', uniqueKey: this.produceUniqueKey() }
        if (this.attributeParamList[$index].attributes.length >= 40) {
          this.$message.warning('该规格名规格值最多40个')
          return
        }
        this.attributeParamList[$index].attributes.push(modelSkuVal)
        this.handleSkuDetailData(this.attributeParamList[$index].attributes)
      })
    },
    // 删除
    handleRemove (type, $index, index, item, items) {
      // type = 1 规格名删除
      if (type === 1) {
        this.addBtnDis = false
        // 获取规格名数据长度
        if (this.attributeParamList.length <= 1) {
          this.$message.warning('规格名不低于1个！')
        } else {
          this.attributeParamList.splice($index, 1)
          this.handleSkuDetailData()
        }
      }

      // type = 2 规格值删除
      if (type === 2) {
        const len = item.attributes.length || 0
        if (len <= 1) {
          this.$message.warning('当前规格名下规格值不能低于1个！')
        } else {
          this.attributeParamList[$index].attributes.splice(index, 1)
          this.handleSkuDetailData()
        }
      }
    },
    // input change
    handleDataChange (val, val2) {
      // 判断是否是规格名、规格值
      const isName = val.hasOwnProperty('attributes')
      const tips = isName ? '规格名' : '规格值'
      let count = 0 // 出现次数
      let valList = []
      let value = ''
      if (isName) {
        // 规格名
        value = val.name
        valList = this.attributeParamList.map(item => item.name)
      } else {
        // 规格值
        valList = val2.attributes.map(item => item.value)
        value = val.value
      }
      valList.forEach(e => {
        if (value && e === value) {
          count++
        }
      })

      if (count > 1) {
        val.isError = true
        this.$message.warning(`${tips}存在重复值`)
      } else {
        val.isError = false
        this.handleSkuDetailData()
      }
    },
    // 批量设置 规格明细数据
    handleBatchSet (row, type, title) {
      const tips = '格式不正确'
      const priceReg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/ // 含零的正整数正则 小数两位
      const sortReg = /^([1-9]\d*|[0]{1,1})$/ // 含零的正整数正则
      let inputPatternReg = ''

      const inputTitle = row.name
      const inputErrorMessage = row.name + tips
      const key = row.key || ''
      if (row.regType === 1) inputPatternReg = sortReg
      if (row.regType === 2) inputPatternReg = priceReg

      this.$prompt('', `批量设置${inputTitle}`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputValue: '',
        inputPattern: inputPatternReg,
        inputErrorMessage: inputErrorMessage
      }).then(({ value }) => {
        this.skuDetailData.forEach(item => {
          item[key] = value
        })
      }).catch(() => { })
    },
    // 规格明细数据处理
    handleSkuDetailData (item) {
      // price: '', // 价格 stock: '', // 库存  costPrice: '', // 成本价 skuCode: '' // 商品编码
      // 规格长度最多为三
      this.dataDealLoading = true
      let dataArr = []
      this.lastTimeSkuData = JSON.parse(JSON.stringify(this.skuDetailData)) // 记录改变的规格明细数据
      const codeList = this.skuDetailData.map(item => item.skuCode)
      this.skuDetailTableHead = []
      this.skuDetailData = []
      try {
        let skuLen1List = this.retrunArr(1)
        let skuLen2List = this.retrunArr(2)
        let skuLen3List = this.retrunArr(3)

        this.attributeParamList.forEach((item, $index) => {
          this.skuDetailTableHead.push(item.name)
        })
        this.skuDetailTableHead = this.skuDetailTableHead.concat(this.tableHead)

        if (skuLen1List && skuLen1List.length >= 1) {
          skuLen1List.forEach(v1 => {
            if (skuLen2List && skuLen2List.length >= 1) {
              skuLen2List.forEach(v2 => {
                if (skuLen3List && skuLen3List.length >= 1) {
                  skuLen3List.forEach(v3 => {
                    dataArr.push(this.skuDetailDataAssign(v1, v2, v3))
                  })
                } else {
                  dataArr.push(this.skuDetailDataAssign(v1, v2))
                }
              })
            } else {
              dataArr.push(this.skuDetailDataAssign(v1))
            }
          })
        }
        // 数量超过600条 当前规格值 删除 后续不操作
        if (dataArr.length >= this.skuDetailDataNum) {
          this.dataDealLoading = false
          this.$message.warning(`规格明细数量不允许超过${this.skuDetailDataNum}条`)
          item.pop()
          this.skuDetailData = this.lastTimeSkuData
          return
        }
        // 相同规格赋值
        dataArr.forEach((e, index) => {
          this.lastTimeSkuData.forEach(i => {
            // 存在第三规格名
            if (skuLen3List.length > 0) {
              if (e.sp1 === i.sp1 && e.sp2 === i.sp2 && e.sp3 === i.sp3) {
                e.usePointLimit = i.usePointLimit
                e.weight = i.weight
                e.price = i.price
                e.costPrice = i.costPrice
                e.skuCode = i.skuCode
                e.stock = i.stock
              }
            } else if (!skuLen3List || skuLen3List.length === 0) {
              // 第三规格名 不存在
              if (e.sp1 === i.sp1 && e.sp2 === i.sp2) {
                e.usePointLimit = i.usePointLimit
                e.weight = i.weight
                e.price = i.price
                e.costPrice = i.costPrice
                e.stock = i.stock
                e.skuCode = i.skuCode
              }
            } else if (!skuLen2List || skuLen2List.length === 0) {
              // 第二规格名 不存在
              if (e.sp1 === i.sp1) {
                e.usePointLimit = i.usePointLimit
                e.weight = i.weight
                e.price = i.price
                e.costPrice = i.costPrice
                e.stock = i.stock
                e.skuCode = i.skuCode
              } else {
                e.skuCode = this.productSnList[index]
              }
            }
          })
        })
        this.skuDetailData = dataArr
        this.skuDetailData.forEach((e, index) => {
          e.skuCode = codeList[index]
        })

        this.dataDealLoading = false
      } catch (error) {
        this.dataDealLoading = false
      }
    },
    // 规格明细赋值
    skuDetailDataAssign (v1, v2, v3) {
      let itemInfo = {
        sp1: v1.value,
        sp2: v2 ? v2.value : '',
        sp3: v3 ? v3.value : '',
        usePointLimit: '',
        price: '',
        costPrice: '',
        weight: '',
        stock: '',
        sale: '',
        skuCode: ''
      }

      return itemInfo
    },
    // 判断是否存在 skuValList
    retrunArr (index) {
      if (!this.attributeParamList || this.attributeParamList.length <= 0) return []
      const skuValList = this.attributeParamList[index - 1] && this.attributeParamList[index - 1].attributes && this.attributeParamList[index - 1].attributes.length >= 1 ? this.attributeParamList[index - 1].attributes : []
      return skuValList
    },
    // 生成唯一uniquekey
    produceUniqueKey () {
      return new Date().getTime()
    },
    handleSetProductSn () {
      this.$nextTick(() => {
        this.skuDetailData.forEach((e, index) => {
          if (!e.skuCode) {
            e.skuCode = this.productSnList[index]
          }
        })
      })
    },
    getSn () {
      const len = 60
      GetProductSn({ count: len, type: 2 }).then(res => {
        this.productSnList = res.data.list || []
      }).catch(() => {
        this.$message.error('获取商品编码失败！')
      })
    },
    // 上传数据
    upEmitData (val) {
      let data = {
        attributeParamList: this.attributeParamList,
        pmsSkuStockVOList: val || this.skuDetailData
      }
      data.attributeParamList.forEach((e, index) => {
        e.attributes.forEach(item => {
          if (index > 0 && item.imageUrl) {
            item.imageUrl = ''
          }
        })
        e.attributeValueList = e.attributes
      })
      this.$emit('upEmitData', data)
    }
  }
}

</script>
<style lang='scss' scoped>
@import '@/styles/sku.scss';
</style>
